springBoot 使用@Value获取配置文件中参数

非静态变量赋值

  • 直接使用@Value("${spring.redis.host}")配置,spring.redis.host为配置文件中参数命名,注意不要忘记加${}
1
2
3
4
5
6
7
8
9
10
11
12
13
@RestController
@RequestMapping("/jedis")
public class JedisDemo1 {

@Value("${spring.redis.host}")
private String host;

@RequestMapping(value ="/hellJedis")
public String hellJedis() {
System.out.println("host:" + host );
return "hello host !!";
}
}

静态变量赋值

  • 使用@Component注解
  • 在set方法上使用@Value
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    @Component
    public class Test {

    private static Integer test;

    public static Integer getTest() {
    return test;
    }
    @Value("${server.port}")
    public void setTest(Integer test) {
    this.test = test;
    }
    }

参考文档:static静态变量使用@Value注入方式

题外话:初次使用,一定得考虑时静态变量和非静态变量。又一坑~~

引入jar

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>5.1.3.RELEASE</version>
</dependency>